<template>
  <div style="width: 100%;overflow: auto;">
    <div v-if="editOpen" style="width: 100%;overflow: auto;">
      <t-table :selected-row-keys="selectedRowKeys" @select-change="(val) => { selectedRowKeys = val }" rowKey="id"
        :data="data" :columns="columns" style="width: 100%;overflow: auto;">

        <template #sort="{ rowIndex }">
          {{ rowIndex + 1 }}
        </template>
        <template #sex="{ row }">
          {{ row.sex | filterByDict(dict.type.sys_user_sex) }}
        </template>
        <template #degree="{ row }">
          {{ row.degree | filterByDict(dict.type.degree) }}
        </template>
        <template #personType="{ row }">
          {{ row.personType | filterByDict(dict.type.kjpt_person_type) }}
        </template>
        <template #profTit="{ row }">
          {{ row.profTit | filterByDict(dict.type.prof_tit) }}
        </template>
        <template #profTitId="{ row }">
          {{ row.profTitId | filterByTree(profTitOptions, children = "children", id = "id", label = "name") }}
        </template>

        <template #empty>
          <span>暂无数据 请点击新增按钮</span>
        </template>
      </t-table>
      <div style="margin-top: 10px" class="btn-group-inline">
        <t-button @click="addMemberAction">新增</t-button>
        <t-button @click="upData">上移</t-button>
        <t-button @click="downData">下移</t-button>
        <t-button @click="updateMemberAction">修改</t-button>
        <t-button @click="delData">删除</t-button>
      </div>
    </div>
    <div v-else>
      <t-table rowKey="id" :data="data" :columns="columns2" style="width: 100%;overflow: auto;">
        <template #sort="{ rowIndex }">
          {{ rowIndex + 1 }}
        </template>
        <template #sex="{ row }">
          {{ row.sex | filterByDict(dict.type.sys_user_sex) }}
        </template>
        <template #degree="{ row }">
          {{ row.degree | filterByDict(dict.type.degree) }}
        </template>
        <template #personType="{ row }">
          {{ row.personType | filterByDict(dict.type.kjpt_person_type) }}
        </template>
        <template #profTit="{ row }">
          {{ row.profTit | filterByDict(dict.type.prof_tit) }}
        </template>
        <template #profTitId="{ row }">
          {{ row.profTitId | filterByTree(profTitOptions, children = "children", id = "id", label = "name") }}
        </template>
      </t-table>
    </div>
    <platform-main-member-edit @updateMemberData="updateMemberData" @addMemberData="addMemberData"
      :header="dialog.header" :oldData="dialog.oldData" :rowIndex="dialog.rowIndex" :editOpen="dialog.editOpen"
      :visible.sync="dialog.open_detail" v-if="dialog.open_detail"></platform-main-member-edit>
  </div>
</template>

<script>
import { getDictList } from "@/api/system/dict/data";
import PlatformMainMemberEdit from "./platform-main-member-edit.vue";

export default {
  dicts: ["prof_tit", "kjpt_person_type", "sys_user_sex", "degree"],
  name: "platform-main-member",
  components: {
    PlatformMainMemberEdit
  },
  props: {
    value: {
      type: Array,
      default: () => [],
    },
    editOpen: {
      type: Boolean,
      default: false
    },
  },
  data () {
    return {
      deptMenuOptions: [],
      companyOptions: [],
      companyLoading: false,
      nameOptions: [],
      leaderLoading: false,
      // dictTypes: {},
      profTitOptions: [],
      selectedRowKeys: [],
      dialog: {
        objId: null,
        header: '',
        oldData: null,
        open_detail: false,
        editOpen: false,
        rowIndex: null
      },
      formData: {
        sort: null,
        name: '',
        isInnerCompany: '1',
      },
      rules: {
        name: [
          {
            required: true,
            message: "名称不能为空",
          },
        ],
        duty: [
          {
            required: true,
            message: "职务不能为空",
          },
        ],
        platformDuty: [
          {
            required: true,
            message: "平台职务不能为空",
          },
        ],
        personType: [
          {
            required: true,
            message: "人才类型不能为空",
          },
        ],
        profTit: [
          {
            required: true,
            message: "职称不能为空",
          },
        ],
        company: [
          {
            required: true,
            message: "所在单位不能为空",
          },
        ],

      },
      data: [],
      columns: [
        {
          colKey: 'row-select',
          type: 'single',
          title: "选择",
          width: 64
        },
        {
          colKey: 'sort',
          title: "序号",
          align: "center",
          width: 64
        },
        {
          colKey: 'name',
          title: "姓名",
          align: "left",
          ellipsis: true,
          width: 80
        },
        {
          colKey: 'sex',
          title: "性别",
          align: "left",
          ellipsis: true,
          width: 80
        },
        {
          colKey: 'idCard',
          title: "身份证",
          align: "left",
          ellipsis: true,
          width: 200
        },
        {
          colKey: 'majorName',
          title: "从事专业",
          align: "left",
          ellipsis: true,
          width: 140
        },
        {
          colKey: 'platformDuty',
          title: "平台职务",
          align: "left",
          ellipsis: true,
          width: 100
        },
        {
          colKey: 'duty',
          title: "职务",
          align: "left",
          ellipsis: true,
          width: 100
        },
        {
          colKey: 'degree',
          title: "学位",
          align: "left",
          ellipsis: true,
          width: 80
        },
        {
          colKey: 'personType',
          title: "人才类型",
          align: "left",
          ellipsis: true,
          width: 200
        },
        {
          colKey: 'profTitId',
          title: "技术职称",
          align: "left",
          width: 100,
          ellipsis: true
        },
        {
          colKey: 'profTit',
          title: "职称等级",
          align: "left",
          width: 100,
          ellipsis: true
        },
        {
          colKey: 'company',
          title: "所在单位名称",
          align: "left",
          ellipsis: true,
          width: 220
        },

      ],
      columns2: [
        {
          colKey: 'sort',
          title: "序号",
          align: "center",
          width: 64
        },
        {
          colKey: 'name',
          title: "姓名",
          align: "left",
          ellipsis: true,
          width: 80
        },
        {
          colKey: 'sex',
          title: "性别",
          align: "left",
          ellipsis: true,
          width: 80
        },
        {
          colKey: 'idCard',
          title: "身份证",
          align: "left",
          ellipsis: true,
          width: 200
        },
        {
          colKey: 'majorName',
          title: "从事专业",
          align: "left",
          ellipsis: true,
          width: 140
        },
        {
          colKey: 'platformDuty',
          title: "平台职务",
          align: "left",
          ellipsis: true,
          width: 100
        },
        {
          colKey: 'duty',
          title: "职务",
          align: "left",
          ellipsis: true,
          width: 100
        },
        {
          colKey: 'degree',
          title: "学位",
          align: "left",
          ellipsis: true,
          width: 80
        },
        {
          colKey: 'personType',
          title: "人才类型",
          align: "left",
          ellipsis: true,
          width: 200
        },
        {
          colKey: 'profTitId',
          title: "技术职称",
          align: "left",
          width: 100,
          ellipsis: true
        },
        {
          colKey: 'profTit',
          title: "职称等级",
          align: "left",
          width: 100,
          ellipsis: true
        },
        {
          colKey: 'company',
          title: "所在单位名称",
          align: "left",
          ellipsis: true,
          width: 220
        },
      ]
    }
  },
  watch: {
    data: {
      deep: true,
      immediate: true,
      handler (val) {
        const newData = this.data.map((val, index) => ({ ...val, sort: index + 1 }))
        this.$emit("input", newData);
      }
    },
    value: {
      deep: true,
      immediate: true,
      handler (val) {
        if (val.length > 0 && this.data.length <= 0) {
          this.data = val;
          // this.data = this.data.map((item,index)=>{
          //   return item.name.split("-")[0]
          //   // if(item.name.split("-")[0]==val.split("-")[0]){
          //   //   index2 = index
          //   // }
          // })
          for (let i = 0; i < this.data.length; i++) {
            this.data[i].name = this.data[i].name.split("-")[0]
          }
        }
      }
    },
  },
  async mounted () {

    // await this.getDataTypes()
    await this.getProfTitTreeSelect()
    await this.getDeptTreeSelect()
  },
  methods: {
    getDeptTreeSelect () {
      return this.$api.system.dept.treeSelectAllIn().then(response => {
        this.deptMenuOptions = response.data
      }).catch(e => {
        this.$message.error(e.toString())
      })
    },
    createCompanyOptions (value) {
      this.companyOptions.push({
        label: `${value}`,
        // label:`1`,
        value
      });
    },
    remoteCompanyMethod (search) {
      this.companyLoading = true;
      this.$api.system.dept.selectAllOutDeptList({ deptName: search }).then(response => {
        this.companyOptions = response.data.map(val => ({
          ...val,
          label: `${val.deptName}`,
          value: val.deptName,
        }))
        this.companyLoading = false;
      }).catch((e) => {
        this.companyLoading = false;
        this.$message.error(e.toString());
      });
    },
    getStatus (status) {
      return status ? "default" : "error"
    },
    createProjectLeaderOptions (value) {
      this.nameOptions.push({
        label: `${value}`,
        value,
        name: value
      });
    },
    remoteProjectLeaderMethod (search) {
      this.leaderLoading = true;
      this.$api.system.member.searchList({ name: search }).then(response => {
        this.nameOptions = response.data.map(val => ({
          ...val,
          label: `${val.name}-${val.idCard}`,
          value: `${val.name}-${val.idCard}`,
          unitName: val.company,
          name: val.name
        }));
        this.leaderLoading = false;
      }).catch((e) => {
        this.leaderLoading = false;
        this.$message.error(e.toString());
      });
    },
    onLeaderNameChange (val, content) {
      const index = this.nameOptions.findIndex(val => content?.option?.id === val.id)
      this.nameOptions[index].label = this.nameOptions[index].name;
      // console.log(this.nameOptions[index])
      this.$set(this.nameOptions, index, this.nameOptions[index])
      // Object.assign(this.formData.projectLeader, content.option)
      // console.log(content?.option?.name)
      let index2 = -1
      this.data.forEach((item, index) => {
        if (item.name.split("-")[0] == val.split("-")[0]) {
          index2 = index
        }
      })
      content.option.name = content.option.label

      this.$set(this.data, index2, content.option)

    },
    getDataTypes () {
      return getDictList(["prof_tit", "kjpt_person_type"]).then(response => {
        this.dictTypes = response.data;
      }).catch((e) => {
        this.$message.error(e.toString());
      });
    },
    getProfTitTreeSelect () {
      return this.$api.system.profTit.list().then(response => {
        this.profTitOptions = this.handleTree(response.data, "id");
      }).catch((e) => {
        this.$message.error(e.toString());
      });
    },
    onProfTitIdChange (val, content) {
      this.data.forEach(item => {
        if (item.profTitId == val) {
          item.profTit = content.node.data.level;
        }
      })
    },
    checkData () {
      // this.$set(this.data[0], 'status', 'error')
      const isValidate = this.data.every((val, index) => {
        Object.keys(val).forEach(item => {
          if (val[item] === null) {
            val[item] = ""
          }
        })
        console.log('----------', val);

        // let myreg = /^[1][3,4,5,7,8][0-9]{9}$/;
        // if (!myreg.test(val.phone)) {
        //   this.$message.error(`第${index + 1}条起草小组成员手机号码格式有误`);
        //   return false;
        // }
        if (val.name === "" || val.duty === "" || val.platformDuty === "" || val.personType === "" || val.profTit === "" || val.company === "") {
          // this.$set(this.data[index], 'status', 'error')
          this.$message.error(`专家人员：第${index + 1}条内容不能为空`);
          return false;
        }
        // if (val.userName == "") {
        //   this.$set(this.data[index], 'status', 'error')
        //   this.$message.error(`起草单位：第${index + 1}条内容不能为空`);
        //   return false;
        // }
        // this.$set(this.data[index], 'status', 'default')
        return true;
      });
      return isValidate;
    },
    addMemberAction () {
      this.dialog.editOpen = false;
      this.dialog.objId = null;
      this.dialog.oldData = null;
      this.dialog.rowIndex = null;
      this.dialog.header = '新增平台主要人员';
      this.dialog.open_detail = true
    },
    addMemberData (data) {
      const newId = Number(new Date().getTime()) + Number(Math.random() * 10)
      this.data.push({ ...data, id: newId })
    },
    updateMemberAction () {
      if (this.selectedRowKeys.length <= 0) {
        this.$message.warning("请选择一行");
        return false;
      }
      const index = this.data.findIndex((val) => val.id === this.selectedRowKeys[0])
      // Object.assign(this.formData,this.data[index])
      // this.formData = this.data8[index]

      this.dialog.rowIndex = index;
      this.dialog.editOpen = true;
      this.dialog.oldData = this.data[index]
      this.dialog.header = "修改平台主要人员"
      this.dialog.open_detail = true;

    },
    updateMemberData (data, rowIndex) {
      this.$set(this.data, rowIndex, data)
    },
    upData () {
      if (this.selectedRowKeys.length <= 0) {
        this.$message.warning("请选择一行");
        return;
      }
      if (this.data[0].id === this.selectedRowKeys[0]) {
        this.$message.warning("已是第一行");
      } else {
        const index = this.data.findIndex((val) => val.id === this.selectedRowKeys[0])
        this.moveInArray(this.data, index, index - 1)
      }
    },
    downData () {
      if (this.selectedRowKeys.length <= 0) {
        this.$message.warning("请选择一行");
        return;
      }
      if (this.data[this.data.length - 1].id === this.selectedRowKeys[0]) {
        this.$message.warning("已是最后一行");
      } else {
        const index = this.data.findIndex((val) => val.id === this.selectedRowKeys[0])
        this.moveInArray(this.data, index, index + 1)
      }
    },
    delData () {
      if (this.selectedRowKeys.length <= 0) {
        this.$message.warning("请选择一行");
        return;
      }
      const index = this.data.findIndex((val) => val.id === this.selectedRowKeys[0])
      this.data.splice(index, 1)
      this.selectedRowKeys = [];
    },
    moveInArray (arr, ffrom, to) {
      // 删除当前的位置
      const item = arr.splice(ffrom, 1);
      // 确保还剩有元素移动
      if (!item.length) {
        this.$message.warning(`There is no item in the array at index ${ffrom}`);
      }
      // 移动元素到指定位置
      arr.splice(to, 0, item[0]);
    },
    onSubmit () {
      this.$refs.form.validate().then((validateResult) => {
        if (validateResult === true) {
          this.data.push({
            id: Number(new Date().getTime()) + Number(Math.random() * 10),
            ...this.formData
          })
          this.$refs.form.reset();
        } else {
          const firstError = Object.values(validateResult)[0]?.[0]?.message;
          this.$message.error(firstError);
        }
      })
    },
  }
}
</script>

<style lang="less" scoped>
/deep/ .t-table td .t-input__tips {
  position: absolute;
}

/deep/ .t-table tr {
  height: 95px;
}

//.t-form__item {
//  margin-bottom: var(--td-comp-margin-xxl);
//  margin-right: 0px
//}</style>
